import qs from 'qs';
import {message} from 'antd';
import {logout} from '../redux/actions/user';
import store from '../redux/store';

const checkStatus = response => {
    if (response.status >= 200 && response.status < 300) {
        return response;
    }
    throw new Error(response.statusText);
};

const parseJSON = response => {
    return response.json();
};

const zwbfetch = (url, options = {}) => {
    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json',
        },
    };
    const newOptions = {...defaultOptions, ...options};
    if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
        newOptions.body = JSON.stringify(newOptions.body);
    } else if (newOptions.method === 'GET' && newOptions.params) {
        url += `?${qs.stringify(newOptions.params)}`;
    }
    newOptions.headers.Authorization = `Bearer ${store.getState().user.token}`;
    return fetch(url, newOptions)
        .then(checkStatus)
        .then(parseJSON)
        .then(response => {
            if (response.code === 0) {
                return response.data;
            } else if (response.code === 401) {
                message.error('登录已过期，请重新登录');
                store.dispatch(logout());
                return Promise.reject(new Error('登录已过期，请重新登录'));
            } else {
                message.error(response.msg);
                return Promise.reject(new Error(response.msg));
            }
        })
        .catch(error => {
            console.error(error);
            message.error(error.message || '请求出错');
            return Promise.reject(error);
        });
};

export default zwbfetch;
